package voa;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import util.FileProcessor;

public class KindleFileProcessor implements FileProcessor {

	public void process(File file) {
		
		LrcFiles lrcFiles = LrcFiles.current();
				
		String inFileName = file.getAbsolutePath();
		String outFileName = getOutputPath(file);

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(new File(inFileName)), "unicode"));

			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(new File(outFileName)), "utf-8"));

			String lineStr = "";
			String sentence = "";
			int line = 0;
					
			String begin = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" + "\n";
			begin += "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "\n";
			begin += "<head>" + "\n";
			begin += "<title>VOA " + lrcFiles.getType() + " English " + lrcFiles.getDate() + "</title>" + "\n";
			begin += "<link rel=\"stylesheet\" href=\"voa.css\" type=\"text/css\" />" + "\n";
			begin += "</head>" + "\n";
			begin += "<body>" + "\n";
			
			
			String end = "</body>\n</html>";
			
			
			writer.write(begin);
			
			while (null != (lineStr = reader.readLine())) {
				
				if (line == 0) {
					
					lineStr = lineStr.substring(4, lineStr.length() - 1);
					String[] heads = lineStr.split(" - ");
					
					String headString = "";
					
					for(int i = 0; i < heads.length; i++){
						
						String head = heads[i];
						
						if(0 == i){
							
							headString += "<br>" + head  + " -- " + lrcFiles.drawDate(file.getName()) + "</br>";
						
						} else {
	
							headString += "<br>" + head  + "</br>";
						}
					}
					
					writer.write("<h4>" + headString + "</h4>\n");

				} else if(line > 3 ){
					
					lineStr = lineStr.substring(10, lineStr.length()).trim();
					
					if(sentence.equals("")){
						sentence += lineStr;
					}else{
						sentence += " " + lineStr;
					}
					
					if(sentence.endsWith(".") || sentence.endsWith("\"") ){
						
						writer.write("<p>" + sentence + "</p>\n");
						sentence = "";
					}
				}
					
				line++;
			}
			
			writer.write(end);

			reader.close();
			writer.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	static public String getOutputPath(File file){
		
		String fileName = file.getName();
		
		String[] strs = fileName.split(".");
		
		String newName = strs[0] + "." + "html";
		
		return file.getParent() + "/" + newName;	
	}
	
}
